package de.justphil.tcg.tcgserver.rest.db.image;

import java.io.File;
import java.io.IOException;

import javax.ws.rs.core.Response;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;

import de.justphil.tcg.tcgserver.commons.config.RestConfig;
import de.justphil.tcg.tcgserver.commons.exceptions.TCGException;
import de.justphil.tcg.tcgserver.commons.i18n.Error;
import static de.justphil.tcg.tcgserver.commons.logging.TCGLogging.*;

public class ImagesDirectory {
	
	private static final Logger log = restLogger(ImagesDirectory.class);

	
	/*
	public static synchronized void init() {
		String ps = File.separator;
		
		File imagesDir = new File(RestConfig.IMAGES_DIR);
		createIfNotExists( imagesDir );
		
		File cardsDir = new File( RestConfig.IMAGES_DIR + ps + RestConfig.CARDS_DIR );
		createIfNotExists( cardsDir );
		
		File propertiesDir = new File( RestConfig.IMAGES_DIR + ps + RestConfig.PROPERTIES_DIR );
		createIfNotExists( propertiesDir );
	}
	
	private static synchronized void createIfNotExists( File f ) {
		if (!f.exists()) {
			f.mkdir();
			log.info("{} created!", f.getAbsolutePath());
		}
		else {
			log.info("{} already exists!", f.getAbsolutePath());
		}
	}
	*/
	
	
	public byte[] getCardImageFile(long cardId) throws TCGException {
		String ps = File.separator;
		
		StringBuilder sb = new StringBuilder(255);
		sb.append(RestConfig.IMAGES_DIR).append(ps).append(RestConfig.CARDS_DIR)
					.append(ps).append(Long.toString(cardId)).append(RestConfig.IMAGE_FILE_ENDING);
		
		log.debug("getCardImageFile() path => {}", sb.toString());
		
		return getImageFile( new File( sb.toString() ) );
	}
	
	public byte[] getPropertyImageFile(long propertyId) throws TCGException {
		String ps = File.separator;
		
		StringBuilder sb = new StringBuilder(255);
		sb.append(RestConfig.IMAGES_DIR).append(ps).append(RestConfig.PROPERTIES_DIR)
					.append(ps).append(Long.toString(propertyId)).append(RestConfig.IMAGE_FILE_ENDING);
		
		log.debug("getPropertyImageFile() path => {}", sb.toString());
		
		return getImageFile( new File( sb.toString() ) );
	}
	
	public byte[] getImageFile( File f ) throws TCGException {
		byte[] bytes = null;
		
		try {
			bytes = FileUtils.readFileToByteArray(f);
		} catch (IOException e) {
			throw new TCGException(Error.CLIENT_ERROR_IMAGE_NOT_FOUND, Response.Status.NOT_FOUND);
		}
		
		return bytes;
	}
	
}
